﻿using Aurora.SingalR.Hubs;
using StackExchange.Redis;

namespace Gateway.UI.Api.Hubs
{
    /// <summary>
    /// 
    /// </summary>
    public static class HubsExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddHubs(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSignalR(config =>
            {
                config.EnableDetailedErrors = true;
                config.ClientTimeoutInterval = TimeSpan.FromMinutes(2);
                config.KeepAliveInterval = TimeSpan.FromMinutes(1);
                config.MaximumReceiveMessageSize = 1024 * 1024 * 10; // 数据包大小10M，默认最大为32K
            })
                //.AddMessagePackProtocol() //二进制传输用的
                // 使用redis做底板 支持横向扩展 Scale-out
                .AddStackExchangeRedis(options =>
                {
                    options.Configuration.ChannelPrefix = new RedisChannel("_signalr_", RedisChannel.PatternMode.Auto);
                    options.ConnectionFactory = async writer =>
                    {
                        var connection = await ConnectionMultiplexer.ConnectAsync(configuration["HubRedis"], writer);
                        connection.ConnectionFailed += (_, e) => { Console.WriteLine("Connection to Redis failed."); };

                        if (connection.IsConnected)
                        {
                            Console.WriteLine("connected to Redis.");
                        }
                        else
                        {
                            Console.WriteLine("Did not connect to Redis");
                        }

                        return connection;
                    };
                });
            services.AddScoped<IHubHandler, HubHandler>();
            services.AddScoped(typeof(HubHandlerProvider));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public static void MapHubs(this IApplicationBuilder app)
        {
            app.UseConfiguredEndpoints(endpoints => { endpoints.MapHubs<MessageHub>(); });
        }
    }
}